package org.nordligulv;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;

import java.io.IOException;

/**
 * User: nordligulv
 * Date: 26.02.11
 * Time: 16:54
 */
public class BeelineBalaceWidgetProvider extends AppWidgetProvider {
    private static final String LOGIN =  "your.login";
    private static final String PASSWORD =  "your.password";

    @Override
    public void onEnabled(Context context) {
        ComponentName thisWidget = new ComponentName(context, BeelineBalaceWidgetProvider.class);
        AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
        int[] ids = widgetManager.getAppWidgetIds(thisWidget);
        Log.d("BALANCE WIDGET", "ENABLED");
        Log.d("BALANCE WIDGET", "WIDGETS " + ids.length);

        Intent updaterIntent = new Intent(context, RepeatingAlarmSerivce.class);
        updaterIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        updaterIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, updaterIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 30 * 60000, pendingIntent);
    }

    @Override
    public void onDisabled(Context context) {
        Log.d("BALANCE WIDGET", "DISABLED");
        Intent updaterIntent = new Intent(context, RepeatingAlarmSerivce.class);
        updaterIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, updaterIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);

        context.stopService(new Intent(context, UpdateService.class));
    }

    public static class UpdateService extends IntentService {
        private static final String TAG = "Beeline balance service";

        private final BeelineBalanceService balanceService = new BeelineBalanceService();
        private String balance = "-";

        public UpdateService() {
            super(TAG);
        }

        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(TAG, "INTENT CALLED");
            int[] ids = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            RemoteViews views = new RemoteViews(getPackageName(), R.layout.widget_loading);
            for (int id : ids) {
                manager.updateAppWidget(id, views);
            }

            try {
                balance = balanceService.get(LOGIN, PASSWORD);
            } catch (IOException e) {
                Log.e(TAG, "Could not retrieve balance", e);
                balance = "-";
            }
            Log.d(TAG, "RETRIEVED BALACE: " + balance);

            Intent updaterIntent = new Intent(this, RepeatingAlarmSerivce.class);
            updaterIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            updaterIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, updaterIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            views = new RemoteViews(getPackageName(), R.layout.widget);
            views.setTextViewText(R.id.widget_text, String.format(getString(R.string.balance_format), balance));
            for (int id : ids) {
                views.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
                manager.updateAppWidget(id, views);
            }
        }
    }

    public static class RepeatingAlarmSerivce extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("ALARM RECEIVER", "TICK!");
            Intent updateIntent = new Intent(context, UpdateService.class);
            updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS));
            context.startService(updateIntent);
        }
    }
}
